type TGetData = {
  params: object;
};
type TPostData = {
  [key in string]: any;
};
const baseUrl: string = 'https://www.ttzxh.icu/api';
const websocketUrl: string = 'wss://www.ttzxh.icu/api';
// const baseUrl: string = 'localhost:8089/api';
const get = (url: string, getData?: TGetData) => {
  const realdata: string = getData ? format(getData) : '';
  return fetch(baseUrl + url + '?' + realdata)
    .then(res => res.json())
    .catch(e => {
      console.log(e);
      Promise.reject(e);
    });
};
const post = (
  url: string,
  postData: FormData | TPostData,
  headers?: RequestInit['headers'],
) => {
  return fetch(baseUrl + url, {
    method: 'post',
    body: postData instanceof FormData ? postData : JSON.stringify(postData),
    headers: headers || {
      'Content-Type': 'application/json',
    },
  })
    .then(res => {
      return res.json();
    })
    .catch(e => Promise.resolve(e));
};
const format = (data: TGetData) => {
  const dataArr = Object.entries(data.params);
  let formatString: Array<string> = [];
  dataArr.forEach(item => {
    formatString.push(`${item[0]}=${item[1]}`);
  });
  return formatString.join('&');
};
const request = {
  get,
  post,
};
export default request;
export {websocketUrl};
